package com.xiaomaoguai.fcp.fcp.utils.mi;

import com.github.xiaomaoguai.xxr.utils.security.RSA;
import com.xiaomaoguai.fcp.fcp.utils.r360.CommonUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * 小米加解密工具
 *
 * @fileName: MiSecurityUtils.java
 * @author: WeiHui
 * @date: 2018/10/8 17:15
 * @version: v1.0.0
 * @since JDK 1.8
 */
@Slf4j
public final class MiSecurityUtils {

	private MiSecurityUtils() {
	}

	public static String generate128AesKey() {
		return AesUtil.genRandomKey();
	}

	/**
	 * 对 key进行加密
	 *
	 * @return 加密的 aesKey
	 */
	public static String encryptForKey(String aesKey, String miPublicKey) {
		try {
			return RSA.encrypt(aesKey, miPublicKey);
		} catch (Exception e) {
			log.error("====>小米对aeskey加密出错[{}]", e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * 对key进行解密
	 *
	 * @param key
	 * @param zaPrivateKey
	 * @return
	 */
	public static String decryptKey(String key, String zaPrivateKey) {
		try {
			return RSA.decrypt(key, zaPrivateKey);
		} catch (Exception e) {
			log.error("====>小米对aeskey解密出错[{}]", e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * 对参数进行加密
	 *
	 * @return 加密参数
	 */
	public static String encryptForBizParam(String param, String aesKey) {
		try {
			return AES.encryptToBase64(param, aesKey);
		} catch (Exception e) {
			log.error("====>小米对业务参数加密出错,aesKey:[{}]", aesKey, e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * 对请求参数进行解密
	 *
	 * @param data
	 * @param aesKey
	 * @return
	 */
	public static String decryptByAesKey(String data, String aesKey) {
		try {
			return AES.decryptFromBase64(data, aesKey);
		} catch (Exception e) {
			log.error("====>小米对业务参数加密出错[{}]", e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * 小米加签
	 *
	 * @param rpcResult    参数
	 * @param zaPrivateKey 私钥
	 * @return 签名
	 */
	public static String doSign(Map<String, String> rpcResult, String zaPrivateKey) {
		String paramsStr = CommonUtil.getSortParams(rpcResult);
		log.info("待签名数据为:{}", paramsStr);
		try {
			String sign = RSA.sign(paramsStr, zaPrivateKey);
			log.info("签名后数据为:" + sign);
			return sign;
		} catch (Exception e) {
			log.error("小米加签异常", e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * 小米验签
	 *
	 * @param plainText   待签明文
	 * @param sign        签名数据
	 * @param miPublicKey 小米公钥
	 * @return
	 */
	public static boolean verifySign(String plainText, String sign, String miPublicKey) {
		try {
			return RSA.checkSign(plainText, sign, miPublicKey);
		} catch (Exception e) {
			log.error("小米验签异常", e);
			throw new RuntimeException(e);
		}
	}

}
